﻿namespace dotnet_notes.Tools
{
    /// <summary>
    /// Word 工具类
    /// </summary>
    public static class WordTool
    {
        /// <summary>
        /// 转换成 Word
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="templatePath">模板路径</param>
        /// <param name="entity">数据对象实例</param>
        /// <param name="placeholder">两侧占位符(默认是 $)</param>
        /// <returns></returns>
        public static Stream ToWord<T>(string templatePath, T entity, char placeholder = '$')
        {
            using var fs = File.OpenRead(templatePath);
            var doc = new XWPFDocument(fs);

            var props = typeof(T).GetProperties();
            foreach (var prop in props)
            {
                var oldValue = placeholder + prop.Name + placeholder;
                var newValue = prop.GetValue(entity)?.ToString();
                doc.FindAndReplaceText(oldValue, newValue);
            }

            var ms = new MemoryStream();
            doc.Write(ms);

            ms.Position = 0;
            return ms;
        }

        /// <summary>
        /// Word 转 PDF
        /// </summary>
        /// <param name="wordStream">Word 文件流</param>
        /// <returns></returns>
        public static Stream ToPdf(Stream wordStream)
        {
            Stream outputStream = new MemoryStream();

            var doc = new Aspose.Words.Document(wordStream);
            doc.Save(outputStream, Aspose.Words.SaveFormat.Pdf);

            outputStream.Position = 0;
            return outputStream;
        }
    }
}
